<?php
namespace App\Services;

use App\Models\UserModel;
use Framework\BaseService;
use Qiniu\Auth;
use Qiniu\Http\Client;
use Qiniu\Rtc\AppClient;

class QiNiuService extends BaseService
{


    private $auth;
    private $bucket;
    private $rtc;
    public function __construct()
    {

        $access_key =  config('filesystems.disks.qiniu.access_key');
        $secret_key = config('filesystems.disks.qiniu.secret_key');
        $this->bucket = config('filesystems.disks.qiniu.bucket');
        $this->auth  = new Auth($access_key,$secret_key);

        $this->rtc = new AppClient($this->auth);
    }


    /**
     * 获取七牛token
     * @return array
     */
    public function getQiNiuToken()
    {
        $policy = null;
        $expires = 86400;
        $url = config('filesystems.disks.qiniu.domains.default');
        $bucket =$this->bucket;
        $token =  $this->auth->uploadToken($bucket,null, $expires, $policy, true);
        return compact('token','url','bucket');
    }



    /**
     * 创建应用
     * @param string $hub 绑定的直播 hub
     * @param string $title app 的名称  注意，Title 不是唯一标识，重复 create 动作将生成多个 app
     * @param int $maxUsers 连麦房间支持的最大在线人数
     * @param bool $noAutoKickUser 禁止自动踢人（抢流），默认为 false
     * @return array
     * @link  https://doc.qnsdk.com/rtn/docs/server_overview#2_1
     */
    public function createApp($hub, $title, $maxUsers = null, $noAutoKickUser = null)
    {

        return  $this->rtc->createApp($hub,$title,$maxUsers,$noAutoKickUser);
    }


    /**
     * 更新一个应用的配置信息
     *
     * @param string $appId app 的唯一标识，创建的时候由系统生成
     * @param string $hub app 的名称，可选
     * @param string $title 绑定的直播 hub，可选，用于合流后 rtmp 推流
     * @param int $maxUsers 连麦房间支持的最大在线人数，可选
     * @param bool $noAutoKickUser 禁止自动踢人，可选
     * @param null $mergePublishRtmp 连麦合流转推 RTMP 的配置，可选择。其详细配置可以参考文档
     * @return array
     * @link  https://doc.qnsdk.com/rtn/docs/server_overview#2_1
     */
    public function updateApp($appId, $hub, $title, $maxUsers = null, $noAutoKickUser = null, $mergePublishRtmp = null)
    {
        return  $this->rtc->updateApp($appId,$hub,$title,$maxUsers,$noAutoKickUser,$mergePublishRtmp);
    }


    /**
     * 获取应用信息
     * @param string $appId
     * @return array
     * @link  https://doc.qnsdk.com/rtn/docs/server_overview#2_1
     */
    public function getApp($appId)
    {
        return  $this->rtc->getApp($appId);
    }


    /**
     * 删除应用
     * @param string $appId app 的唯一标识，创建的时候由系统生成
     * @return array
     * @link  https://doc.qnsdk.com/rtn/docs/server_overview#2_1
     */
    public function deleteApp($appId)
    {
        return  $this->rtc->deleteApp($appId);
    }



    /**
     * 获取房间内用户列表
     *
     * @param string $appId app 的唯一标识，创建的时候由系统生成
     * @param string $roomName 操作所查询的连麦房间
     * @return array
     * @link https://doc.qnsdk.com/rtn/docs/server_overview#2_2
     */
    public function listUser($appId, $roomName)
    {
        return  $this->rtc->listUser($appId,$roomName);
    }


    /**
     * 指定一个用户踢出房间
     * @param string $appId app 的唯一标识，创建的时候由系统生成
     * @param string $roomName 连麦房间
     * @param string $userId 操作所剔除的用户
     * @return mixed
     * @link https://doc.qnsdk.com/rtn/docs/server_overview#2_2
     */
    public function kickUser($appId, $roomName, $userId)
    {
        return  $this->rtc->kickUser($appId,$roomName, $userId);
    }


    /**
     * 停止一个房间的合流转推
     * @param string $appId
     * @param string $roomName
     * @return array
     * @link https://doc.qnsdk.com/rtn/docs/server_overview#2_2
     */
    public function stopMerge($appId, $roomName)
    {
        return  $this->rtc->stopMerge($appId,$roomName);
    }


    /**
     * 获取应用中活跃房间
     * @param string $appId 连麦房间所属的 app
     * @param null $prefix 所查询房间名的前缀索引，可以为空。
     * @param int $offset 分页查询的位移标记
     * @param int $limit 此次查询的最大长度
     * @return array
     * @link https://doc.qnsdk.com/rtn/docs/server_overview#2_2
     */
    public function listActiveRooms($appId, $prefix = null, $offset = null, $limit = null)
    {
        return  $this->rtc->listActiveRooms($appId,$prefix,$offset,$limit);
    }


    /**
     * 生成加入房间的令牌
     * @param string $appId app 的唯一标识，创建的时候由系统生成
     * @param string $roomName 房间名称，需满足规格 ^[a-zA-Z0-9_-]{3,64}$
     * @param string $userId 请求加入房间的用户 ID，需满足规格 ^[a-zA-Z0-9_-]{3,50}$
     * @param int $expireAt 鉴权的有效时间，传入以秒为单位的64位 Unix 绝对时间
     * @param string $permission 该用户的房间管理权限，"admin" 或 "user"，默认为 "user"
     * @return string
     * @link https://doc.qnsdk.com/rtn/docs/server_overview#1
     */
    public function appToken($appId, $roomName, $userId, $expireAt, $permission)
    {
        return  $this->rtc->appToken($appId,$roomName,$userId,$expireAt,$permission);
    }


    /**
     * IM用户登录
     * @param $username
     * @return array|mixed|string|null
     */
    public function imRegister($username)
    {
        $endpoint = 'https://s-1-3-s-api.maximtop.cn'.'/user/register/v2';
        $access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJjeWV4emZsYWZrZWkiLCJzdWIiOiIyMjg4IiwiY2x1c3RlciI6MCwicm9sZSI6MiwiaWF0IjoxNjU2MjMxMTg4fQ.l1d2cSe5KBJwNl9ZjgTprkU8OovBLgn5e0sigKFUjzj3WEKGFeEQuGoOM-UNKCkgmqNrkqtm2g_xacWXC9hJUw';
        $app_id = 'cyexzflafkei';
        $params = array();
        $params['username'] = $username;
        $params['password'] = '123456';
        $body = json_encode($params);
        $header['Content-Type'] = 'application/json';
        $header['access-token'] = $access_token;
        $header['app_id'] = $app_id;
        $res = $this->post($endpoint,$body,$header);
        //echo $res[0]['code'];
        //echo $res[0]['data']['user_id'];
        return $res;
    }


    /**
     * 获取IM用户TOKEN
     * @param $user_id
     * @return array|mixed|string|null
     */
    public function getImuserToken($user_id)
    {
        $qniu_uid = UserModel::query()->where(['id'=>$user_id])
            ->select('qiniu_uid')
            ->first();
        if(!$qniu_uid['qiniu_uid'])
        {
            return '当前用户未生成qiniu_uid';
        }
        $endpoint = 'https://s-1-3-s-api.maximtop.cn'.'/token/id';
        //$access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJjeWV4emZsYWZrZWkiLCJzdWIiOiIyMjg4IiwiY2x1c3RlciI6MCwicm9sZSI6MiwiaWF0IjoxNjU2MjMxMTg4fQ.l1d2cSe5KBJwNl9ZjgTprkU8OovBLgn5e0sigKFUjzj3WEKGFeEQuGoOM-UNKCkgmqNrkqtm2g_xacWXC9hJUw';
        $app_id = 'cyexzflafkei';
        $params = array();
        $params['user_id'] = intval($qniu_uid['qiniu_uid']);
        $params['password'] = '123456';
        $body = json_encode($params);
        $header['Content-Type'] = 'application/json';
        //$header['access-token'] = $access_token;
        $header['app_id'] = $app_id;
        $res = $this->post($endpoint,$body,$header);
        return $res;
    }


    /**
     *通过用户名和密码取普通用户token
     * @param $user_id
     * @return array|mixed|string|null
     */
    public function getTokenUser()
    {
       /* $qniu_uid = UserModel::query()->where(['id'=>$user_id])
            ->select('qiniu_uid')
            ->first();
        if(!$qniu_uid['qiniu_uid'])
        {
            return '当前用户未生成qiniu_uid';
        }*/
        $endpoint = 'https://s-1-3-s-api.maximtop.cn'.'/token/user';
        //$access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJjeWV4emZsYWZrZWkiLCJzdWIiOiIyMjg4IiwiY2x1c3RlciI6MCwicm9sZSI6MiwiaWF0IjoxNjU2MjMxMTg4fQ.l1d2cSe5KBJwNl9ZjgTprkU8OovBLgn5e0sigKFUjzj3WEKGFeEQuGoOM-UNKCkgmqNrkqtm2g_xacWXC9hJUw';
        $app_id = 'cyexzflafkei';
        $params = array();
        $params['name'] = '39dev_俺弟弟';
        $params['password'] = '123456';
        $body = json_encode($params);
        $header['Content-Type'] = 'application/json';
        //$header['access-token'] = $access_token;
        $header['app_id'] = $app_id;
        $res = $this->post($endpoint,$body,$header);
        return $res;
    }


    /**
     * 获取IM用户信息
     * @param $user_id
     * @return array|mixed|string|null
     */
    public function getImUserProfile($user_id)
    {
        $endpoint = 'https://s-1-3-s-api.maximtop.cn'.'/user/profile';
        $app_id = 'cyexzflafkei';
        //$header['user_id'] = intval($user_id);
        $header['Content-Type'] = 'application/json';
        $header['app_id'] = $app_id;
        $res = $this->get($endpoint,$header);
        return $res;
    }


    /**
     * 创建IM群聊
     * @param $user_id
     * @param string|null $description
     * @param string|null $name
     * @return array|mixed|string|null
     */
    public function createImGroup(int $user_id,string $description=null,string $name=null)
    {
        $qniu_uid = UserModel::query()->where(['id'=>$user_id])
            ->select('qiniu_uid')
            ->first();
        if(!$qniu_uid['qiniu_uid'])
        {
            return '当前用户未生成qiniu_uid';
        }
        $endpoint = 'https://s-1-3-s-api.maximtop.cn'.'/group/create';
        $app_id = 'cyexzflafkei';
        $access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJjeWV4emZsYWZrZWkiLCJzdWIiOiIyMjg4IiwiY2x1c3RlciI6MCwicm9sZSI6MiwiaWF0IjoxNjU2MjMxMTg4fQ.l1d2cSe5KBJwNl9ZjgTprkU8OovBLgn5e0sigKFUjzj3WEKGFeEQuGoOM-UNKCkgmqNrkqtm2g_xacWXC9hJUw';
        $params = array();
        $params['avatar'] = ''; //群头像
        $params['description'] = $description; //群描述
        $params['name'] = $name; //群名称
        $params['type'] = 2; //群类型 1表示公开群，0表示私有群, 2表示聊天室
        $body = json_encode($params);
        $header['Content-Type'] = 'application/json';
        $header['access-token'] = $access_token;
        $header['app_id'] = $app_id;
        $header['user_id'] = intval($qniu_uid['qiniu_uid']);
        $res = $this->post($endpoint,$body,$header);
        return $res;
    }


    /**
     * 模拟post请求
     * @param $url
     * @param $body
     * @param $header
     * @return mixed|string|null
     */
    private function post($url, $body, $header)
    {
        $ret = Client::post($url, $body, $header);
        if (!$ret->ok()) {
            return $ret->error;
        }
        $r = ($ret->body === null) ? array() : $ret->json();
        return array($r, null);
    }


    /**
     * 模拟get请求
     * @param $url
     * @param $header
     * @return array|mixed|string|null
     */
    private function get($url,$header)
    {
        $ret = Client::get($url, $header);
        if (!$ret->ok()) {
            return $ret->error;
        }
        $r = ($ret->body === null) ? array() : $ret->json();
        return array($r, null);
    }



}
